package middleware

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
)

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 记录请求开始时间
		start := time.Now()

		// 处理请求
		c.Next()

		// 计算耗时
		duration := time.Since(start)

		// 收集日志信息
		status := c.Writer.Status()
		method := c.Request.Method
		path := c.Request.URL.Path
		clientIP := c.ClientIP()

		// 记录日志信息
		log.Info().
			Str("method", method).
			Str("path", path).
			Dur("duration", duration).
			Int("status", status).
			Str("client_ip", clientIP).
			Msg(fmt.Sprintf("[%s] %s - %d", method, path, status))
	}
}
